package api

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type ParamAPI struct {
}

func (api *ParamAPI) StringQuery(ctx *gin.Context) {
	name := ctx.Query("name")
	age := ctx.DefaultQuery("age", "18")
	email := ctx.DefaultQuery("email", "abc@163.com")
	ctx.JSON(http.StatusOK, gin.H{
		"name":  name,
		"age":   age,
		"email": email,
	})
}

func (api *ParamAPI) StringArrayQuery(ctx *gin.Context) {
	names := ctx.QueryArray("names")
	ctx.JSON(http.StatusOK, gin.H{
		"names": names,
	})
}

func (api *ParamAPI) PathParam(ctx *gin.Context) {
	name := ctx.Param("name")
	age := ctx.Param("age")
	ctx.JSON(http.StatusOK, gin.H{
		"name": name,
		"age":  age,
	})
}

func (api *ParamAPI) BodyForm(ctx *gin.Context) {
	name := ctx.PostForm("name")
	age := ctx.PostForm("age")
	ctx.JSON(http.StatusOK, gin.H{
		"name": name,
		"age":  age,
	})
}

type UserParam struct {
	Name string `json:"name" form:"name" uri:"name"`
	Age  int    `json:"age" form:"age" uri:"age"`
}

func (api *ParamAPI) Bind(ctx *gin.Context) {
	var user UserParam
	if err := ctx.ShouldBind(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "绑定参数到结构体成功", "data": user})
}

func (api *ParamAPI) BindUri(ctx *gin.Context) {
	var user UserParam
	if err := ctx.ShouldBindUri(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "绑定参数到结构体成功", "data": user})
}
